package com.geek.factory.utils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class NumberToChinese {
    private static final String[] NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] UNITS = {"", "拾", "佰", "仟"};
    private static final String[] BIG_UNITS = {"", "万", "亿"};

    public static String convert(double number) {
        if (number == 0) {
            return "零元整";
        }

        BigDecimal bd = new BigDecimal(number);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

        long integerPart = bd.longValue();
        int decimalPart = bd.remainder(BigDecimal.ONE).multiply(new BigDecimal(100)).intValue();

        StringBuilder result = new StringBuilder();

        if (integerPart > 0) {
            result.append(convertInteger(integerPart)).append("元");
        }

        if (decimalPart > 0) {
            result.append(convertDecimal(decimalPart));
        } else {
            result.append("整");
        }

        return result.toString();
    }

    private static String convertInteger(long number) {
        if (number == 0) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        int unitIndex = 0;

        while (number > 0) {
            long section = number % 10000;
            String sectionStr = convertSection((int) section);

            if (section != 0) {
                result.insert(0, sectionStr + BIG_UNITS[unitIndex]);
            } else if (unitIndex > 0 && result.length() > 0 && !result.toString().startsWith("零")) {
                result.insert(0, "零");
            }

            number /= 10000;
            unitIndex++;
        }

        return result.toString();
    }

    private static String convertSection(int section) {
        if (section == 0) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        int unitIndex = 0;

        while (section > 0) {
            int digit = section % 10;

            if (digit != 0) {
                result.insert(0, UNITS[unitIndex] + NUMBERS[digit]);
            } else if (result.length() > 0 && !result.toString().startsWith("零")) {
                result.insert(0, "零");
            }

            section /= 10;
            unitIndex++;
        }

        return result.toString();
    }

    private static String convertDecimal(int decimal) {
        int jiao = decimal / 10;
        int fen = decimal % 10;

        StringBuilder result = new StringBuilder();

        if (jiao > 0) {
            result.append(NUMBERS[jiao]).append("角");
        }

        if (fen > 0) {
            result.append(NUMBERS[fen]).append("分");
        }

        return result.toString();
    }
}